<template>
  <div class="header">
        <div class="header-left fl">
           <i class="iconfont icon-shizhongclock74" style="font-size: 28px;"></i>
           <!-- 时间 -->
           <span class="time">{{ time }}</span>
           <!-- 日期 -->
           <span class="date">{{ date }}</span>
           <!-- 周末 -->
           <span class="week">{{ week }}</span>
        </div>
        <div class="header-center fl">
            <div class="header-title" >
              氮化镓紫外局放监测系统
            </div>
            <div class="header-img"></div>
        </div>
        <div class="header-right fl">
          <!-- 阈值设置 -->
          <el-dropdown trigger="click" style="margin-right: 20px;">
            <!-- 超级管理员 -->
            <span class="el-dropdown-link superAdmin">    
              <el-icon size="21px" style="margin-right:5px;" color="#2980b9"><el-icon><Grid /></el-icon></el-icon>
              阈值设置<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="item in orderList" :key="item.id" @click="openPup(item.id)">{{ item.orderName }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
    </el-dropdown>
          <el-dropdown trigger="click">
            <!-- 超级管理员 -->
            <span class="el-dropdown-link superAdmin">    
              <el-icon size="21px" style="margin-right:5px;" color="#2980b9"><UserFilled /></el-icon>
              管理员<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="toAdmin">后台管理</el-dropdown-item>
              <el-dropdown-item @click="openSetting">用户设置</el-dropdown-item>
              <el-dropdown-item @click="exitLogin">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
    </el-dropdown>
    <div class="fullscreen">
      <i @click="taggleFullscreen" v-if="!isFullscreen" class="iconfont icon-quanping" style="color:#3481b7;font-size:19px;" title="全屏"></i>
      <i @click="taggleFullscreen" v-else class="iconfont icon-tuichuzhuanhuan" style="color:#3481b7;font-size:19px;" title="退出全屏"></i>
    </div>
      </div>
      <div class="header-bottom fl"></div>
    </div>
  <el-dialog
      v-model="settingVisible"
      title="用户设置"
      width="24%"
      draggable="true"
  >
    <el-form label-width="3rem;" :model="userSetting">
      <el-form-item label="数据刷新速率：">
        <el-input-number v-model="userSetting.speed" :min="20" class="speedCss"></el-input-number>
      </el-form-item>
      <el-form-item label="快速恢复：">
         <el-button type="danger" @click="openSelect(1)" :disabled="resetPoniter > 0">
          <span v-if="resetPoniter === 0">CLICK ME</span>
          <span v-else>{{ resetPoniter }}</span>
        </el-button>
      </el-form-item>
      <el-form-item label="唤醒/睡眠：">
         <el-button type="success" @click="openSelect(2)" :disabled="wakeUpPainter > 0">
          <span v-if="wakeUpPainter === 0">唤醒</span>
          <span v-else>{{ wakeUpPainter }}</span>
        </el-button>
        <el-button type="warning" @click="openSelect(3)" :disabled="sleepPainter > 0" >
          <span v-if="sleepPainter === 0">睡眠</span>
          <span v-else>{{ sleepPainter }}</span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="settingVisible = false">取消</el-button>
        <el-button type="primary" @click="changeSetting">
           确定
        </el-button>
      </span>
    </template>
  </el-dialog>
<!-- 选择那个模块进行唤醒 -->
<el-dialog
    v-model="selectVisable"
    title="请先选择那些模块进行操作"
    width="30%"
    draggable="true"
  >
  <div class="module_list" v-if="isConfirm === 2">
      <div class="module_item" v-for="item in module_store.sleepModule" :key="item.id" @click="selectModule_id(item.id)">
        <div class="img">
          <img src="../../assets/module.active.png" v-if="item.isChecked"/>
          <img src="../../assets/module.png" v-else/>
        </div>
        <p>模块{{ item.id }}</p>
      </div>
    </div>
    <div class="module_list" v-else>
      <div class="module_item" v-for="item in module_store.wakeupModule" :key="item.id" @click="selectModule_id(item.id)">
        <div class="img">
          <img src="../../assets/module.active.png" v-if="item.isChecked"/>
          <img src="../../assets/module.png" v-else/>
        </div>
        <p>模块{{ item.id }}</p>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="selectVisable = false">取消</el-button>
        <el-button type="primary" @click="confirm">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
    <!-- 给传感器设置阈值（出压力以外） -->
    <el-dialog
      v-model="visible1"
      :title="'监测点' + device_currentId + currentName+'阈值设置'"
      width="25%"
      draggable="true"
  >
    <div class="slider-demo-block">
      <span class="demonstration">正常值</span>
      <el-slider v-model="currentMin" :min="tempMin" :max="currentMax" show-input/>
    </div>
    <div class="slider-demo-block">
      <span class="demonstration">警告值</span>
      <el-slider v-model="currentMax" :min="currentMin"
      :max="currentAlarm" show-input/>
    </div>
    <div class="slider-demo-block">
      <span class="demonstration">报警值</span>
      <el-slider v-model="currentAlarm" :min="currentMax" :max="tempAlarm" show-input/>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible1 = false">取消</el-button>
        <el-button type="primary" @click="changeValue">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 给压力传感器设置阈值 -->
  <el-dialog
    v-model="visible2"
    :title="'监测点' +device_currentId + '压力阈值修改'"
    width="25%"
    draggable="true"
  >
  <div class="slider-demo-block">
      <span class="demonstration">正常值</span>
      <el-slider v-model="currentAlarm" :min="currentMax" :max="tempAlarm" show-input/>
    </div>
    <div class="slider-demo-block">
      <span class="demonstration">警告值</span>
      <el-slider v-model="currentMax" :max="currentAlarm" :min="currentMin" show-input/>
    </div>
    <div class="slider-demo-block">
      <span class="demonstration">报警值</span>
      <el-slider v-model="currentMin" :min="tempMin" :max="currentMax" show-input/>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible2 = false">取消</el-button>
        <el-button type="primary"  @click="changeValue">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

function launchFullscreen(element) {
 if(element.requestFullscreen) {
  element.requestFullscreen();
 } else if(element.mozRequestFullScreen) {
  element.mozRequestFullScreen();
 } else if(element.webkitRequestFullscreen) {
  element.webkitRequestFullscreen();
 } else if(element.msRequestFullscreen) {
  element.msRequestFullscreen();
 }
}

function exitFullscreen() {
 if(document.exitFullscreen) {
  document.exitFullscreen();
 } else if(document.mozCancelFullScreen) {
  document.mozCancelFullScreen();
 } else if(document.webkitExitFullscreen) {
  document.webkitExitFullscreen();
 }
}
    import {ref,onMounted, reactive} from 'vue'
    import {storeToRefs} from 'pinia'
    import {userStore} from '../../store/user'
    import {useRouter} from 'vue-router';
    import {moduleStore} from '../../store/module'
    import { getCurrentInstance } from 'vue';
    let module_store = moduleStore()
    let {module_list,selectModule,device_currentId} = storeToRefs(module_store)
    import { IhttpReturn } from '../../until/interface';
    let {proxy} = getCurrentInstance()
    let store = userStore() // 本地数据存储
    let router = useRouter() // 本地的路由
    let {localWebsocket} = storeToRefs(store)
    let selectVisable = ref<boolean>(false) //控制选择那个模块
    let isConfirm = ref<number>(0) // 1 => 快速回复 2 => 睡眠和唤醒
    const weekList = ["星期一","星期二","星期三","星期四","星期五","星期六","星期天"]
    let time = ref('') // 时间
    let date = ref('') // 日期
    let week = ref('') // 周末 

    let visible1 = ref<boolean>() // 除压力以外阈值设置对话框
    let visible2 = ref<boolean>() // 设置压力阈值设置对话框
    let currentName = ref<string>("") // 获取设备的名称
    let currentMax = ref<number>() // 获取设备的最大值
    let currentMin = ref<number>() // 获取设备的最小值
    let currentAlarm = ref<number>() // 获取设备的报警值
    let tempAlarm = ref<number>() // 零时存放最大值
    let pressMin = ref<number>() // 零时存放压力的最小值
    let setting = reactive([]) 
    let tempMin = ref<number>() // 零时存放最小值
      // 阈值设置 
      type obj = {
        orderName: string,
        id: number,
        refName: string
      }
  const orderList:Array<obj> = [
    {
      orderName: "紫外",
      id: 1,
      refName: "uvcRef"
    },
    {
      orderName: "红外",
      id: 2,
      refName: "infRef"
    },
    {
      orderName: "振动",
      id: 3,
      refName: "accRef"
    },
    {
      orderName: "温度",
      id: 4,
      refName: "temRef"
    },  {
      orderName: "湿度",
      id: 5,
      refName: "humRef"
    },
    {
      orderName: "压力",
      id: 6,
      refName: "preRef"
    }
  ]
  let type_id = ref(0)
    // 打开设置阈值对话框
 const openPup = (id:number) => {
    type_id.value = id - 1
    if (id == 6) {
        let index = device_currentId.value - 1
				currentName.value = setting[index][id - 1].name // 获取设备的名称
				currentMax.value = setting[index][id - 1].normal_high // 获取设备的最大值
				currentMin.value = setting[index][id - 1].normal_low  // 获取设备的最小值
				currentAlarm.value = setting[index][id - 1].alarm // 获取设备的报警值
				tempAlarm.value = setting[index][id - 1].tempAlarm// 零时存取最大值
				pressMin.value = setting[index][id - 1].tempMin /// 零时存取最小值
				visible2.value = true // 显示面板
    } else {
        let index = device_currentId.value - 1
        currentName.value = setting[index][id - 1].name // 获取设备的名称
        currentMax.value = setting[index][id - 1].normal_high // 获取设备的最大值
        currentMin.value = setting[index][id - 1].normal_low  // 获取设备的最小值
        currentAlarm.value = setting[index][id - 1].alarm // 获取设备的报警值
        tempAlarm.value = setting[index][id - 1].tempAlarm // 零时存取最大值
        tempMin.value = setting[index][id-1].tempMin // 零时存放最小值
        visible1.value = true
    }
 }
    // 修改阈值
    const changeValue = async () => {
      let {data:res}:{data:IhttpReturn} = await proxy.$insideHttp.post("/socket/changeSerialport",{id:type_id.value + 1,min:currentMin.value,max:currentMax.value,alarm:currentAlarm.value,device_id:[device_currentId.value]})
      if (res.code !== 200) return proxy.$message({showClose: true,message: res.msg,type: "warning"})
      store.changeValue({id:type_id.value,min:currentMin.value,max:currentMax.value,alarm:currentAlarm.value,module_id: device_currentId.value })
      proxy.$message({showClose: true,message: res.msg,type: "success"})
        visible1.value = false
        visible2.value = false
   }
    const toAdmin = ():void => {
        router.push("/admin")
    }
    const emit = defineEmits(['resetData','closeTimer','startTimer',"taggleDevice","resetView"])
    let currentTime = ref<string>('') // 系统的时间
    let userSetting:{speed:number} = reactive({
      speed: store.speed
    })
    let drawer = ref<boolean>(false)
    let isDisabled = ref<boolean>(false)
    let timer = reactive(null) // 定时器
    let resetPoniter = ref(0) // 快速恢复的时间
    let wakeUpPainter = ref(0) //唤醒的时间
    let sleepPainter = ref(0) // 睡眠的时间
    let currentId = ref(1) // 当前模块id编号
    let isFullscreen = ref(false) // 控制页面是否全屏
    let openSelect = (id:number) => {
      selectVisable.value = true
      isConfirm.value = id
    }
    let confirm = () => {
      let bool:boolean = selectModule.value.some(item => item.isChecked)
      if (!bool) return proxy.$message({showClose: true,message: "至少选中一个模块",type: "warning"}) 
      let selectArr:number[] = []
      selectModule.value.forEach(item => {
        if (item.isChecked) {
          selectArr.push(item.id)
        }
      })
      if (isConfirm.value === 1) {
          // 快速回复
          console.log('快速恢复')
          resetDevice(selectArr)
      } else if(isConfirm.value === 2) {
         // 唤醒和睡眠
         wackUpDevice(selectArr)
      } else {
        sleepDevice(selectArr)
      }
      selectVisable.value = false
      selectModule.value.forEach(item => item.isChecked = false)
      module_store.sleepModule.forEach(item => item.isChecked = false)
      module_store.wakeupModule.forEach(item => item.isChecked = false)
    }
    onMounted(() => {
      // 初始化系统的当前时间
    setting = store.setting
     timer = setInterval(async () => {
          let {data:res}:{data:IhttpReturn} = await proxy!.$insideHttp.get("/socket/addRunDate")
          if (res.code !== 200) {
             // 需要重新请求数据
             emit('resetData')
          }
      },60*1000)

      setInterval(() => {
        let date1 = new Date()
        time.value = date1.toLocaleTimeString()
        date.value = date1.toLocaleDateString().replace(/\//g,"-")
        week.value = weekList[(date1.getDay() - 1)]
      },1000)
    })
    // 改变用户选择参数
    const changeSetting = async () => {
      store.changeSpeed(userSetting.speed)    
      await proxy.$insideHttp.post('/socket/changeSpeed',{speed: userSetting.speed})
      settingVisible.value = false   
    }
    let settingVisible = ref<boolean>(false) // 控制设置面板的显示或者隐藏
    // 打开用户的设置面板
    const openSetting = () => {
      settingVisible.value = true
    }
     // 快速回复按钮
    const resetDevice = async (selectArr:Array<number>) => {
      // @ts-ignore
      let {data:res}:{data:IhttpReturn} = await proxy.$insideHttp.post("/socket/resetDevice",{selectArr})
       if (res.code !== 200) return proxy.$message({showClose: true,message: res.msg,type: "warning"})
       resetPoniter.value = 10
       
       let timer = setInterval(() => {
        if (resetPoniter.value > 0) {
          resetPoniter.value --
        } else {
          clearInterval(timer)
        }
       },1000)

    }

    const sleepDevice = async (selectArr:Array<number>) => {
      selectArr.forEach(item => {
        // @ts-ignore
        selectModule.value[item - 1].status = false
      })
      await proxy.$insideHttp.post('/socket/sleepDevice',{selectArr})
      sleepPainter.value = 10
      wakeUpPainter.value = 1
       let timer = setInterval(() => {
        if (sleepPainter.value > 1) {
          sleepPainter.value --
        } else {
          sleepPainter.value = 0
          clearInterval(timer)
          wakeUpPainter.value = 0
        }
       },1000)

    }
    const wackUpDevice = async (selectArr:Array<number>) => {
      selectArr.forEach(item => {
        // @ts-ignore
        selectModule.value[item - 1].status = true
      })
        await proxy.$insideHttp.post('/socket/wakeUpDevice',{selectArr})
        wakeUpPainter.value = 10
        sleepPainter.value = 1
       let timer = setInterval(() => {
        if (wakeUpPainter.value > 1) {
          wakeUpPainter.value --
        } else {
          wakeUpPainter.value = 0
          clearInterval(timer)
          sleepPainter.value = 0
        }
       },1000)
    }
    // 退出登录
    const exitLogin = async () => {
      localWebsocket.value.close()
      await proxy.$outsideHttp.put("/user/updateLoginStatus",{status: 0,token: store.userInfo.token})
      store.exitUser()
      router.push("/login")
    }
    // 改变选中状态
     const changeChecked = (id:number) => {
        module_list.value.forEach(item => item.isChecked = false)
        module_list.value[id - 1].isChecked = true
        proxy.notifySuccess("切换到"+ module_list.value[id-1].deviceName )
        currentId.value = id
        emit("taggleDevice",id)
     }

    // 选种改变那个模块的阈值
    const selectModule_id = (id:number) => {
      selectModule.value.forEach(item => {
        if (item.id === id) {
            item.isChecked = !item.isChecked
        }
      })
    }

    // 全屏显示页面
    const taggleFullscreen = () => {
      if (!isFullscreen.value) {
         launchFullscreen(document.documentElement)
         isFullscreen.value = true
      } else {
          exitFullscreen()
          isFullscreen.value = false
      }
      emit("resetView")
    }

</script>

<style lang="less" scoped>
.fl {
    float: left;
}
.speedCss {
  width: 160px;
}

// 头部的一些样式
.header {
    width: 100%;
    height: 80px;
    background-image: linear-gradient(to bottom, #20427a, #10152b);
   .header-left {
    width: 25%;
    height: 60px;
    color: white;
    display: flex;
    align-items: center;
    padding-left: 10px;
    padding-top: 10px;
    span {
      margin-right: 10px;
    }
    .time {
      margin-left: 10px;
      font-size: 20px;
    }
     .el-icon {
       font-weight: bold;
     }
}
.header-center {
    width: 50%;
    height: 70px;
    /* border: 1px solid red; */
    position: relative;
    .header-title {
    text-align: center;
    color: #ffffff;
    font-size: 28px;
    text-shadow: 0 0 4px #00d8ff;
    line-height: 30px;
    padding: 5px 0px;
}
 .header-img {
    background: url(../../assets/images/head.gif) no-repeat center center;
    background-size: 100%;
    height: 100%;
    width: 100%;
    position: absolute;
    top: 23px;
}
}
.header-right {
    width: 25%;
    height: 65px;
    line-height: 80px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #fff;
    padding-right: 10px;
    font-size: 18px;
    .setting {
      display: flex;
      align-items: center;
      margin-right: 20px;
      font-size: 14px;
      img {
        width: 25px;
        height: 20px;
        margin-right: 10px;
      }
    }
    .el-dropdown {
      height: 30px;
      border: none!important;
      .el-dropdown-link {
        display: flex;
        align-items: center;
        color: #fff;
        &:hover{
        border: none;
      }
      }
    }
    .fullscreen {
      width: 70px;
      text-align: center;
    }
}
.header-bottom {
    width: calc(100% - 8px);
    height: 5px;
    background: url(../../assets/images/header.png) no-repeat;
    background-size: calc(100% - 3px) 100%;
    padding: 0 3px;
    margin-left: 3px;
}
}

// 菜单样式
.menu {
        width: 100%;
        list-style: none;
        display: flex;
        line-height: 60px;
        a {
            color: #fff;
            flex:1;
            background: url("../../assets/images/bnt.png") no-repeat center;
            display: flex;
            justify-content: center;
            text-decoration: none;
        }
}

.drawer-main {
  height: 400px;
  display: grid;
  grid-template-columns: repeat(4,1fr);
  grid-template-rows: repeat(4,1fr);
  .module_item {
    display: flex;
    flex-direction: column;
    .img {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 70px;
        height: 70px;
      }
    }
    p {
      height: 30px;
      width: 100%;
      text-align: center;
    }
  }
}
.module_list {
  height: 300px;
  display: grid;
  grid-template-columns: repeat(6,1fr);
  grid-template-rows: repeat(4,1fr);
  .module_item {
    display: flex;
    flex-direction: column;
    .img {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 40px;
        height: 40px;
      }
    }
    p {
      height: 30px;
      width: 100%;
      text-align: center;
    }
  }
}
</style>